package com.yzy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzy.common.Code;
import com.yzy.controller.dto.StuResetPasswordDTO;
import com.yzy.entity.Student;
import com.yzy.exception.ServiceException;
import com.yzy.mapper.StudentMapper;
import com.yzy.service.IStudentService;
import com.yzy.utils.StuTokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * StudentServiceImpl
 *
 * @author 杨子宇
 * @createTime 2023-04-18
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Resource
    private StudentMapper studentMapper;

    public List<Student> findAll() {
        return list();
    }

    public Student findById(Integer id) {
        return getById(id);
    }

    public boolean insertOrUpdate(Student user) {
        return saveOrUpdate(user);
    }

    public boolean deleteById(Integer id) {
        return removeById(id);
    }

    public boolean deleteStudents(List<Integer> ids) {
        return removeByIds(ids);
    }

    public Page<Student> findPage(Integer pageNum, Integer pageSize,
                                  String username,
                                  String nickname,
                                  String email,
                                  String phone,
                                  String address,
                                  String signature) {
        Page<Student> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            queryWrapper.or().like("username", username);
        }
        if (!"".equals(nickname)) {
            queryWrapper.or().like("nickname", nickname);
        }
        if (!"".equals(email)) {
            queryWrapper.or().like("email", email);
        }
        if (!"".equals(phone)) {
            queryWrapper.or().like("phone", phone);
        }
        if (!"".equals(address)) {
            queryWrapper.or().like("address", address);
        }
        if (!"".equals(signature)) {
            queryWrapper.or().like("signature", signature);
        }
        return page(page, queryWrapper);
    }

    public void importFile(MultipartFile file) {
        InputStream is;
        try {
            is = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ExcelReader reader = ExcelUtil.getReader(is);


        /*
          方式1，要求表头必须是英文，跟JavaBean的属性对应
          List<User> users = reader.readAll(User.class);
         */

        // 方法2，忽略表头中文
        List<List<Object>> lists = reader.read(1);
        List<Student> students = CollUtil.newArrayList();
        for (List<Object> row : lists) {
            Student student = new Student();
            student.setUsername(row.get(0).toString());
            student.setNickname(row.get(1).toString());
            student.setEmail(row.get(2).toString());
            student.setPhone(row.get(3).toString());
            student.setAddress(row.get(4).toString());
            student.setSignature(row.get(5).toString());
            students.add(student);
        }

        saveBatch(students);
    }

    public void exportFile(HttpServletResponse response) {
        ExcelWriter writer = null;
        ServletOutputStream out = null;
        try {
            // 查询全部数据
            List<Student> list = list();
            // 通过工具类创建writer
            writer = ExcelUtil.getWriter();
            // 自定义标题别名
            writer.addHeaderAlias("username", "用户名");
            writer.addHeaderAlias("password", "密码");
            writer.addHeaderAlias("nickname", "昵称");
            writer.addHeaderAlias("email", "邮箱");
            writer.addHeaderAlias("phone", "电话");
            writer.addHeaderAlias("address", "地址");
            writer.addHeaderAlias("signature", "个性签名");
            writer.addHeaderAlias("createTime", "注册时间");

            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(list, true);

            // 设置浏览器响应头格式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("学生信息", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            // 写出数据
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    public Student stuLogin(Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", student.getUsername());
        queryWrapper.eq("password", student.getPassword());
        Student one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            throw new ServiceException(Code.code_500, "系统错误！");
        }

        if (one != null) {
            BeanUtil.copyProperties(one, student, true);

            // 设置学生token
            String token = StuTokenUtils.getToken(one);
            student.setToken(token);

            return student;
        } else {
            throw new ServiceException(Code.code_600, "用户名或密码错误！");
        }
    }

    public Student stuRegister(Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", student.getUsername());

        Student one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            throw new ServiceException(Code.code_500, "系统错误！");
        }

        if (one == null) {
            save(student);
        } else {
            throw new ServiceException(Code.code_600, "用户已存在！");
        }

        return student;
    }

    public Student findOne(String username) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }

    public Student upDataInfo(Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", student.getId());
        update(student, queryWrapper);

        return student;
    }

    public void updatePassword(StuResetPasswordDTO stuResetPasswordDTO) {
        int update = studentMapper.updatePassword(stuResetPasswordDTO);
        if (update < 1){
            throw new ServiceException(Code.code_401,"原密码错误！");
        }
    }

    public Student resetPassword(Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", student.getUsername());

        Student one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            throw new ServiceException(Code.code_500, "系统错误！");
        }

        if (one == null) {
            throw new ServiceException(Code.code_600, "要找回的用户不存在！");
        } else {
            update(student,queryWrapper);
        }

        return student;
    }
}
